<?php
namespace App\Http\Controllers\Pc;

use App\Models\BaseModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon; //时间
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
class IndexController extends Controller{
/////////////////////////////////////////////// 首页
////////////////////// 七牛云
	/**
	 * 获取七牛云token
	 */
	public function qiniu_token(){
		//上传图片到七牛云
		$Qiniu = new \App\Libs\wrapper\Qiniu();
		$return = $Qiniu->upload_token();
//		var_dump($return);exit;
		if(is_array($return)){
			$this->back('获取成功', '200', $return);
		}else{
			$this->back('获取失败');
		}
	}
	
	/*
	 * 阿里云oss
	*/
	public function oss_add(Request $request){
		$data = $request->all();
		$file = $_FILES;
		
		
		//上传图片到七牛云
		$oss = new \App\Libs\wrapper\Aliyunoss();
		$return = $oss->oss_upimg($file);
		var_dump($return);exit;
		if(is_array($return)){
			$this->back('获取成功', '200', $return);
		}else{
			$this->back('获取失败');
		}
	}
	
	


////////////////////// 首页
	/**
	 * 菜单列表
	 * @param user_id 用户id
	 */
	public function menu_list(Request $request){
		//验证参数
		$this->validate($request, [
			'user_id' => 'required| integer',
		], [
			'user_id.required' => 'user_id为空',
			'user_id.integer' => 'user_id必须是整型数字',
		]);
		
		$data = $request->all();
		
		//所有菜单列表
		$sql  = "select pr.*
				       from xt_role_user_join ruj
				       left join (select prj.role_id, prj.power_id, m.*
				                         from xt_powers_role_join prj
				                         inner join xt_powers p on p.Id=prj.power_id and p.type=1
				                         inner join (select *
				                         					from xt_menus
				                         					order by serial_number asc
				                         			  ) m on m.identity = p.identity
				                  ) as pr on pr.role_id = ruj.role_id
				       where ruj.user_id={$data['user_id']}
				       group by pr.power_id
				       order by pr.serial_number";
		$menu_list = json_decode(json_encode(db::select($sql)),true);
		
		//获取一级菜单
		$sql = "select *
			       from xt_menus
			       where fid=0
			       order by serial_number asc";
		$menuone_list = json_decode(json_encode(db::select($sql)),true);

		foreach ($menuone_list as $k=>$v){
			$menuone_list[$k]['children'] = array();
			$menuone_list[$k]['is_show'] = 0;
			foreach ($menu_list as $k1=>$v1){
				if($v1['fid'] == $v['Id']){
					$menuone_list[$k]['is_show'] = 1;
					$menuone_list[$k]['children'][] = $v1;
				}else if($v1['identity'] == $v['identity']){
					$menuone_list[$k]['is_show'] = 1;
				}
			}
		}
		
		$this->back('成功', 200, $menuone_list);
	}

    /**
     * @Desc: 菜单初始化
     * @param Request $request
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/2/21 10:59
     */
    public function getMenuInitList(Request $request)
    {
        //验证参数
        $this->validate($request, [
            'user_id' => 'required| integer',
        ], [
            'user_id.required' => 'user_id为空',
            'user_id.integer' => 'user_id必须是整型数字',
        ]);
        $data = $request->all();

        // 获取登陆人的角色
        $roleData = DB::table('xt_role_user_join')->where('user_id', $data['user_id'])->select('role_id')->get()->toArray();

        $role = array_column($roleData,'role_id');
        // 获取角色绑定的权限id

        $powerIds = DB::table('xt_powers_role_join')->whereIn("role_id",$role)->select('power_id')->distinct()->get()->map(function ($v){
            return (array)$v;
        })->toArray();
        // echo implode(',',$powerIds);
        // return 1;
        // 根据权限id获取类型为查询权限的信息
        $power = DB::table('xt_powers as p')
            ->whereIn('Id', $powerIds)
            ->where('type', 1)
            ->select('identity')
            ->get()
            ->map(function ($v){
                return (array)$v;
            })
            ->toArray();
        // 获取权限对应的菜单路由
        $menu = DB::table('xt_menus as m')
            ->whereIn('identity', $power)
            ->select()
            ->orderBy('serial_number', 'asc')
            ->get()
            ->map(function ($v){
                return (array)$v;
            })
            ->toArray();
        // 获取所有菜单路由，包括顶级路由
        $result = $this->_formatMenuInitList($menu);

        // 顶级权限增加is_show参数
        foreach ($result as &$item){
            $item['is_show'] = 1;
        }

        return $this->back('成功', 200, $result);
    }

    /**
     * @Desc:格式化菜单数据
     * @param $list
     * @return mixed
     * @author: Liu Sinian
     * @Time: 2023/2/23 9:25
     */
    public function _formatMenuInitList($list)
    {
        $menuIds = [];
        foreach ($list as $item){
            $menuIds[] = $item['Id'];
            if ($item['fid'] == 0){
                continue;
            }else{
                // 三级菜单最多查询两次即可找到fid=0，若有更多层级可以改成递归方法
                $_menu = DB::table('xt_menus')->where('Id', $item['fid'])->select()->orderBy('serial_number', 'asc')->get()->map(function ($v){return (array)$v;})->toArray();
                if ($_menu[0]['fid'] == 0){
                    $menuIds[] = $_menu[0]['Id'];
                }else{
                    $_menu = DB::table('xt_menus')->where('Id', $_menu[0]['fid'])->select()->orderBy('serial_number', 'asc')->get()->map(function ($v){return (array)$v;})->toArray();
                    $menuIds[] = $_menu[0]['Id'];
                }
            }
        }
        // 查询菜单
        $menuList = DB::table('xt_menus')->whereIn('Id', array_unique($menuIds))->select()->orderBy('serial_number', 'asc')->get()->map(function ($v){return (array)$v;})->toArray();
        // 构造菜单数据
        $result = $this->_getTree($menuList, 0);

        return $result;
    }

    /**
     * @Desc:递归返回下级菜单
     * @param $data
     * @param $fid
     * @return mixed
     * @author: Liu Sinian
     * @Time: 2023/2/23 9:25
     */
    public function _getTree($data, $fid = 0)
    {
        $tree = [];
        foreach($data as $k => $v)
        {
            if($v['fid'] == $fid)
            {
                $v['child'] = $this->_getTree($data, $v['Id']);
                $tree[] = $v;
                unset($data[$k]);
            }
        }

        return $tree;
    }
	
	/**
	 * 未读消息
	 * @param user_id 用户id
	 */
	public function tiding_not(Request $request){
		$data = $request->all();
//		var_dump($data);exit;
		$sql = "select count(*) as num
					from tidings
					where user_js={$data['user_info']['Id']} and is_read=1";
		$num = json_decode(json_encode(db::select($sql)),true);
		
		$this->back('成功', 200, $num[0]);
	}

    /**
     * 消息弹窗
     * @param user_id 用户id
     */
    public function tiding_task(Request $request){
        $data = $request->all();
        $user_id = $data['user_id']??0;
        $tiding = null;

        $lenth = Redis::LLEN('tiding_key:'.$user_id);

        // var_dump($user_id);

        if($lenth == 0){
            $this->back('成功', 200);
        }

        for($i=0;$i<$lenth;$i++){
            $key = Redis::RPOP('tiding_key:'.$user_id);
            $tiding = Redis::HGet('tiding:'.$user_id,$key);
            if($tiding) {
                $tiding = json_decode($tiding,true);
                $tiding['disabled'] = 0;
                if ($tiding['object_type'] == 5){
                    $fasin = db::table('amazon_fasin_message')->where('id', $tiding['object_id'])->first();
                    if (empty($fasin)){
                        $tiding['disabled'] = 1;
                    }else{
                        $tiding['object_id'] = $fasin->fasin;
                        $count = mb_strlen($tiding['content']) > 100 ? 100 : mb_strlen($tiding['content']);
                        $str = strip_tags($tiding['content']);
                        $cont = mb_substr($str, 0, $count, "utf-8");
                        if (mb_strlen($tiding['content']) > 100){
                            $cont = $cont.'...';
                        }
                        $tiding['content'] = $cont;
                    }
                }


                Redis::Lpush('tiding_key:'.$user_id, $key);
                $this->back('成功', 200, $tiding);
            }else{
                $this->back('成功', 200);
            }
        }

//        $where = "user_js={$data['user_info']['Id']} and is_read=1";
//        if(!empty($data['Id'])){
//            $where .= " and Id > {$data['Id']}" ;
//        }
//        $sql = "select * from tidings where $where
//					order by Id asc limit 1";
//        $tiding = json_decode(json_encode(db::select($sql)),true);

    }
	
	
	

////////////////////// 权限
	
	/**
	 * 权限验证
	 * @param user_id 用户id
	 * @param identity 权限标识 array('user_add', 'user_update', 'order_update')
	 */
	public function powers_checking(Request $request){
		$this->validate($request, [
			'user_id' => 'required| integer',
		], [
			'user_id.required' => 'user_id为空',
			'user_id.integer' => 'user_id必须是整型数字',
		]);
		
		$data = $request->all();
		$return = $this->powers($data);
//		var_dump($return);exit;
		if(is_array($return)){
			$this->back('成功', '200', $return);
		}else{
			$this->back('权限验证获取失败');
		}
	
	}

    /**
     * spu图片
     * @param spu
     */
    public function get_spu_img(Request $request){
        $data = $request->all();
        $base = new BaseModel();
        $spu = $base->GetNewSpu($data['spu']);
        $img = $base->getSpuImg($spu);
        if($img){
            $this->back('成功', 200, $img);
        }else{
            $this->back('失败', 500);
        }

    }
	
	
	
	
	

    //说明文档列表
	public function GetReadMeList(Request $request){
        $data = $request->all();

        $list = db::table('readme');
        if(isset($data['name'])){
            $list = $list->where('name','like','%'.$data['name'].'%')->orwhere('text','like','%'.$data['name'].'%');
        }
        $list = $list->where('fid',0)->orderby('sort','asc')->select('id','name','sort','fid','user_id','create_time')->get();

        foreach ($list as $v) {
            $v->children = db::table('readme')->where('fid',$v->id)->orderby('sort','asc')->select('id','name','sort','fid','user_id','create_time')->get()??[]; 
            $v->user = Db::table('users')->where('Id', $v->user_id)->first()->account??'';
            # code...
        }
        $this->back('成功', 200, $list);
    }
	

    
    //说明文档列表
	public function GetReadMeDetail(Request $request){
        $data = $request->all();

        $list = db::table('readme')->where('id',$data['id'])->first();
        // if(isset($data['name'])){
        //     $list = $list->where('name','like','%'.$data['name'].'%')->orwhere('text','like','%'.$data['name'].'%');
        // }
        // $list = $list->where('fid',0)->orderby('sort','asc')->get();

        // foreach ($list as $v) {
        //     $v->children = db::table('readme')->where('fid',$v->id)->orderby('sort','asc')->get()??[]; 
        //     $v->user = Db::table('users')->where('Id', $v->user_id)->first()->account??'';
        //     # code...
        // }
        $this->back('成功', 200, $list);
    }



	//新增修改文档列表
    public function SaveReadMe(Request $request){
        $data = $request->all();
        $list = db::table('readme');

        $i['name'] = $data['name'];
        $i['text'] = $data['text']??'';
        $i['sort'] = $data['sort']??0;
        $i['fid'] = $data['fid']??0;
        $i['user_id'] = $data['user_id']??0;
        if(isset($data['id'])){
            $i['create_time'] = date('Y-m-d H:i:s',time());
            $list = $list->where('id',$data['id'])->update($i);
        }else{
            $i['update_time'] = date('Y-m-d H:i:s',time());
            $list = $list->insert($i);
        }
        $this->back('成功', 200);
    }
	

    //文档1级类目
    public function ReadMeCate(){
        $list = db::table('readme')->where('fid',0)->orderby('sort','desc')->get();
        $this->back('成功', 200, $list);
    }


	
    //删除文档列表
	public function DelReadMe(Request $request){
        $data = $request->all();

        if(isset($data['id'])){  
             db::table('readme')->where('id',$data['id'])->delete();
        }

        $this->back('成功', 200);
    }
}//